/*  utils.cpp
 * Copyright (C) 2010, Francisco Claude & Patrick Nicholson, all rights reserved.
 *
 * Francisco Claude & Patrick Nicholson <(fclaude|p3nichol)@cs.uwaterloo.ca>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "utils.h"

size_t writeChainsDes(vector<vector<Point*>*> & chains, ofstream & outfile) {
  size_t totalPoints = 0;
  size_t nrChains = chains.size();
  PointXCmpDes cmp;
  outfile.write((char*)&nrChains,sizeof(size_t));
  for(size_t i=0; i<chains.size(); i++) {
    size_t chainLength = chains[i]->size();
    sort(chains[i]->begin(),chains[i]->end(),cmp);
    outfile.write((char*)&chainLength,sizeof(size_t));
    double * chainDouble = new double[2*chainLength];
    for(size_t j=0; j<chainLength; j++) {
      chainDouble[2*j] = chains[i]->at(j)->getX();
      chainDouble[2*j+1] = chains[i]->at(j)->getY();
      totalPoints++;
    }
    outfile.write((char*)chainDouble,2*sizeof(double)*chainLength);
    delete [] chainDouble;
  }
  return totalPoints;
}

size_t writeChainsAsc(vector<vector<Point*>*> & chains, ofstream & outfile) {
  size_t totalPoints = 0;
  size_t nrChains = chains.size();
  PointXCmpDes cmp;
  outfile.write((char*)&nrChains,sizeof(size_t));
  for(size_t i=0; i<chains.size(); i++) {
    size_t chainLength = chains[i]->size();
    sort(chains[i]->begin(),chains[i]->end(),cmp);
    outfile.write((char*)&chainLength,sizeof(size_t));
    double * chainDouble = new double[2*chainLength];
    for(size_t j=0; j<chainLength; j++) {
      chainDouble[2*j] = chains[i]->at(j)->getX();
      chainDouble[2*j+1] = chains[i]->at(j)->getY();
      totalPoints++;
    }
    outfile.write((char*)chainDouble,2*sizeof(double)*chainLength);
    delete [] chainDouble;
  }
  return totalPoints;
}

void freeChains(vector<vector<Point*>*> & chains) {
  for(size_t i=0; i<chains.size(); i++) {
    delete chains[i];
  }
}

